<?php
class SeminarAccounts_Controller extends AdminController {

    public $REGISTRATION_LIST_UUID = 'admin/seminarAccounts/registrationList';
    public $CANCELLED_REGISTRATION_LIST_UUID = 'admin/seminarAccounts/cancelledRegistrationList';
    public $UNCONFIRMED_REGISTRATION_LIST_UUID = 'admin/seminarAccounts/unconfirmedRegistrationList';
    
    /** @var SeminarAccountsData */
    public $data;
    
    public function __construct() {
        parent::__construct('registration');
        $this->setDefaultListOrder('id');
        
        $this->data = $this->getSessionData()->getSeminarAccountsData();
        $this->data->organization = $this->dao->getById('organization', $this->data->organization['id']);
    }
    
    public function index() {

        if (! $this->data->seminar) {
            $this->redirectToList('error.recordNotFound');
        }
        
        // Load registrations of the organization
        if ($this->data->organization) {
        	$accountingData = $this->getSeminarService()->getOrgAccountingData($this->data->seminar['id'], $this->data->organization['id']);
        	$this->addViewData($accountingData);
        }
        else {
        	$this->redirect('/admin/seminarAccounts/selectOrganizationForm');
        }
        
        $this->renderSubview('/admin/seminarAccounts/seminarAccountsOverview');
    }
    
    public function init() {
        $seminarId = $this->input->get('seminarId');
        $paymentType = $this->input->get('paymentType');
        
        // Basic validation
        if (! valid::isId($seminarId) || ($paymentType != '' && $paymentType != 'onArrival' )) {
            $this->redirectToList('error.invalidId');
        }
        
        if ($this->data->seminar && $seminarId != $this->data->seminar[id]) {
            $this->data->clear();
        }
        
        if ($paymentType) {
            $this->data->paymentType = $paymentType;
        }

        // Fill the models
        $this->data->seminar = $this->dao->fetchSeminar($seminarId, $this->getL10nLanguageCode());
        if (! $this->data->seminar) {
            $this->redirectToList('error.recordNotFound');
        }
        
        $this->redirect('/admin/seminarAccounts/selectOrganizationForm');
    }
    
    private function redirectToIndex() {
        $this->redirect('/admin/seminarAccounts/index');
    }
    
    public function selectOrganizationForm() {
        // Basic validation
        if (! $this->data->seminar) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->selectOrganizationData();
        
        $this->renderSubview('/admin/seminarAccounts/seminarAccountsSelectOrganization');
    }
    
    private function selectOrganizationData() {
    	$this->viewData['countryList'] = $this->dao->queryAll(
    			'SELECT DISTINCT c.code, c.name, c.name_native, c.code ' .
    			'FROM payment_acceptance pa ' .
    			'JOIN organization org ON pa.organization_id = org.id ' .
    			'JOIN country c ON org.country_code = c.code ' .
    			'WHERE pa.seminar_id = :seminar_id ' .
    			'AND (pa.accepts_cash = :accepts OR pa.accepts_bank_transfer  = :accepts) ' .
    			'ORDER BY org.name',
    			array(
    					'seminar_id' => $this->data->seminar['id'],
    					'accepts' => sql::$TRUE,
    			));
    	
    	// Load organizations for each country.
    	foreach ($this->viewData['countryList'] as &$country) {
    		$country['organizationList'] = $this->dao->queryAll(
    				'SELECT o.*, pa.confirmed_at as payment_acceptance_confirmed_at ' .
    				'FROM organization o ' .
    				'JOIN payment_acceptance pa ON o.id = pa.organization_id AND pa.seminar_id = :seminar_id ' .
    				'WHERE country_code = :countryCode ' .
    				'AND (pa.accepts_cash = :accepts OR pa.accepts_bank_transfer  = :accepts) ' .
    				'ORDER BY name',
    				array(
    						'countryCode' => $country['code'],
    						'seminar_id' => $this->data->seminar['id'],
    						'accepts' => sql::$TRUE)
    		);
    	}
    }
    
    public function selectOrganization() {
        $organizationId = $this->input->get('organizationId');

        if (! $this->data->seminar) {
            $this->redirectToList('error.recordNotFound');
        }

        if ($organizationId) {
            $this->data->organization = $this->dao->getById('organization', $organizationId);
        }
        
        $this->redirectToIndex();
    }
    
    protected function redirectToList($errorKey=NULL) {
        if ($errorKey) {
            $this->msg->error($errorKey);
        }
        $this->redirect('/admin/seminar/all');
    }
    
    public function confirmForm() {
    	return $this->renderMySubview('seminarAccountsConfirm');
    }
    
    public function confirm() {
    	$paymentAcceptance = $this->dao->getPaymentAcceptance($this->data->seminar['id'], $this->data->organization['id']);
    	$paymentAcceptance['confirmed_at'] = time();
    	$paymentAcceptance['confirmed_by_id'] = $this->getAuthUser('id');
    	$paymentAcceptance['confirmation_notes'] = $_POST['confirmation_notes'];
    	$entity = new PaymentAcceptanceEntity($paymentAcceptance);
    	$this->dao->updateEntity($entity);
    	
    	$this->redirect('/admin/seminarAccounts/index');
    }
}